package chapter1.view;

import chapter1.util.SingletonFactory;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Scanner;

public class ManageMode {
    public static final String MENU = """
            -------------
               管理模式
            -------------
            | 0 退出系统  |
            | 1 部门管理  |
            | 2 角色管理  |
            | 3 用户管理  |
            | 4 设置密码  |
            -------------
            请输入选项：""";
    //输出主界面菜单
    public static Scanner input;
    private static String code;
    String password;
    static String content;


    static {
        input = new Scanner(System.in);
        try {
            content = Files.readString(Paths.get("D:\\java\\code.java"));
            code = content.trim();
        } catch (IOException e) {
            System.err.println("无法读取密码文件");
        }

    }

    private final DeptView deptView;
    private final RoleView roleView;
    private final UserView userView;


    private ManageMode() {
        deptView = SingletonFactory.getInstance(DeptView.class);
        roleView = SingletonFactory.getInstance(RoleView.class);
        userView = SingletonFactory.getInstance(UserView.class);
    }



    public  void show() {
        String menuChoice;
        System.out.print("请输入密码：");
        password = input.nextLine();
        if (!password.equals(code)) {
            System.out.println("密码错误！");
            return;
        }else{
            System.out.println("密码正确！");
            do {
                System.out.print(MENU);
                menuChoice = input.nextLine();
                switch (menuChoice) {
                    case "0" -> System.out.println("成功退出系统，欢迎再次使用！");
                    case "1" -> deptView.show();
                    case "2" -> roleView.show();
                    case "3" -> userView.show();
                    case "4" -> set();
                    default -> System.out.print("输入非法，请输入正确的菜单编号！");
                }
            } while (!"0".equals(menuChoice));

        }
    }


    public void set()  {
        String temp;
        System.out.print("请输入原密码：");
        temp = input.nextLine();
        if (!temp.equals(code)) {
            System.out.println("原密码错误！");
        } else {
            try {
                System.out.print("请输入新密码：");
                temp = input.nextLine();
                System.out.println("设置成功！");
                writePasswordToFile(temp);
                content = Files.readString(Paths.get("D:\\java\\code.java"));
                code = content.trim();
            } catch (IOException e) {
                System.out.println("无法读取密码文件");
            }
        }
    }

    private static void writePasswordToFile(String newCode) {
        try {
            // 写入文件，覆盖原有内容
            Files.writeString(Paths.get("D:\\java\\code.java"), newCode.trim());
        } catch (IOException e) {
            System.err.println("写入密码文件失败：" + e.getMessage());
        }
    }
}
